package cn.hdustea.shopNavigation;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.MyOrientationListener;
import com.baidu.mapapi.PermissionUtils;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapBaseIndoorMapInfo;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.IndoorPoiOverlay;
import com.baidu.mapapi.overlayutil.IndoorRouteOverlay;
import com.baidu.mapapi.search.core.PoiDetailInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorInfo;
import com.baidu.mapapi.search.poi.PoiIndoorOption;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorPlanNode;
import com.baidu.mapapi.search.route.IndoorRouteLine;
import com.baidu.mapapi.search.route.IndoorRoutePlanOption;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.walknavi.WalkNavigateHelper;
import com.baidu.mapapi.walknavi.adapter.IWEngineInitListener;
import com.baidu.mapapi.walknavi.adapter.IWNaviCalcRouteListener;
import com.baidu.mapapi.walknavi.adapter.IWRoutePlanListener;
import com.baidu.mapapi.walknavi.model.WalkRoutePlanError;
import com.baidu.mapapi.walknavi.params.RouteNodeType;
import com.baidu.mapapi.walknavi.params.WalkNaviLaunchParam;
import com.baidu.mapapi.walknavi.params.WalkRouteNodeInfo;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.hdustea.shopNavigation.adapter.BaseStripAdapter;
import cn.hdustea.shopNavigation.adapter.PoiSearchAdapter;
import cn.hdustea.shopNavigation.entity.IndoorPlanBean;
import cn.hdustea.shopNavigation.ui.view.main.ChildActivity;
import cn.hdustea.shopNavigation.view.StripListView;

public class MainActivity extends AppCompatActivity {
    private String bid = "15460148487993500760";
    private static boolean isPermissionRequested = false;
    private MapView mapView = null;
    private BaiduMap baiduMap = null;
    private BaseStripAdapter stripAdapter;
    private StripListView stripListView;
    private LinearLayout linearLayoutFloor = null;
    private EditText editTextSearch = null;
    private ConstraintLayout constraintLayoutSearch = null;
    private ConstraintLayout constraintLayoutMapView = null;
    private MapBaseIndoorMapInfo mapBaseIndoorMapInfo = null;
    private CardView cardViewTypes = null;
    private CardView cardViewTips = null;
    private CardView cardViewPoiInfo = null;
    private LocationClient locationClient = new LocationClient(this);
    private FloatingActionButton floatingActionButtonLocation = null;
    private BDLocation location = null;
    private PoiSearchAdapter poiSearchAdapter = null;
    private RecyclerView recyclerViewTips = null;
    private IndoorRouteLine.IndoorRouteStep currentStep = null;
    private PoiSearch poiSearch = null;
    private OnGetPoiSearchResultListener tipListener = null;
    private RoutePlanSearch routePlanSearch = null;
    private List<IndoorRouteLine> routeLines = null;
    private List<PoiIndoorInfo> searchedPoiIndoorInfos = null;
    private String startFloorId = null;
    private String endFloorId = null;
    private ConstraintLayout constraintLayoutNavigation = null;
    private IndoorRouteOverlay overlay = null;
    private IndoorPoiOverlay poiOverlay = null;
    private TextView textViewNavigationDetail = null;
    private CardView cardViewNavigationTitle = null;
    private Button buttonStartNavigation = null;
    private Button buttonCancelRoute = null;
    private TextView textViewNavigationTitle = null;
    private CardView cardViewNavigation = null;
    private CardView cardViewSearch = null;
    private TextView textViewPoiName = null;
    private TextView textViewPoiAddress = null;
    private Button buttonNavigation = null;
    private Button buttonDetail = null;
    private PoiIndoorInfo clickedMapPoiInfo = null;
    private String tempClickedFloorId = null;
    private IndoorPlanBean startNodeBean = null;
    private IndoorPlanBean endNodeBean = null;
    private InputMethodManager manager = null;
    private ImageView imageViewPreviousFloor = null;
    private ImageView imageViewNextFloor = null;
    private ConstraintLayout constraintLayoutMapPoi = null;
    private TextView textViewMapPoiTitle = null;
    private Button buttonCancelMapPoi = null;
    private RecognizerDialog iatDialog;
    private ImageView imageViewVoiceMap = null;
    private LocationListener locationListener = null;

    private MyOrientationListener myOrientationListener = null;
    private int mXDirection;   //此刻的x值，方向由传感器测出，范围0~360，为手机方向与北极的角度


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        manager = (InputMethodManager) getSystemService(MainActivity.this.INPUT_METHOD_SERVICE);
        initAdapters();
        initViews();
        initMap();
        setupMap();
        initOrientationListener();
        initVoice();
        initListeners();
        if (getIntent().getExtras() != null) {
            // 获取从店铺传来的名字信息
            String str = getIntent().getStringExtra("searchText").split("\\(")[0];
            editTextSearch.setText(str);
        }
    }

    private void initAdapters() {
        stripAdapter = new BaseStripAdapter(this);
        poiSearchAdapter = new PoiSearchAdapter(this, new ArrayList<PoiIndoorInfo>());
    }

    private void initViews() {
        mapView = findViewById(R.id.mapView);
        linearLayoutFloor = findViewById(R.id.linearLayoutFloor);
        stripListView = new StripListView(this);
        linearLayoutFloor.addView(stripListView);
        editTextSearch = findViewById(R.id.editTextSearch);
        constraintLayoutSearch = findViewById(R.id.constraintLayoutSearch);
        constraintLayoutMapView = findViewById(R.id.constraintLayoutMapView);
        cardViewTypes = findViewById(R.id.cardViewTypes);
        cardViewTips = findViewById(R.id.cardViewTips);
        cardViewPoiInfo = findViewById(R.id.cardViewPoiInfo);
        floatingActionButtonLocation = findViewById(R.id.floatingActionButtonLocation);
        recyclerViewTips = findViewById(R.id.recyclerViewTips);
        textViewNavigationDetail = findViewById(R.id.textViewNavigationDetail);
        constraintLayoutNavigation = findViewById(R.id.constraintLayoutNavigation);
        cardViewNavigationTitle = findViewById(R.id.cardViewNavigationTitle);
        buttonCancelRoute = findViewById(R.id.buttonCancelRoute);
        buttonStartNavigation = findViewById(R.id.buttonStartNavigation);
        textViewNavigationTitle = findViewById(R.id.textViewNavigationTitle);
        cardViewNavigation = findViewById(R.id.cardViewNavigation);
        cardViewSearch = findViewById(R.id.cardViewSearch);
        textViewPoiName = findViewById(R.id.textViewPoiName);
        textViewPoiAddress = findViewById(R.id.textViewPoiAddress);
        buttonNavigation = findViewById(R.id.buttonNavigation);
        buttonDetail = findViewById(R.id.buttonDetail);
        imageViewPreviousFloor = findViewById(R.id.imageViewPreviousFloor);
        imageViewNextFloor = findViewById(R.id.imageViewNextFloor);
        constraintLayoutMapPoi = findViewById(R.id.constraintLayoutMapPoi);
        textViewMapPoiTitle = findViewById(R.id.textViewMapPoiTitle);
        buttonCancelMapPoi = findViewById(R.id.buttonCancelMapPoi);
        imageViewVoiceMap = findViewById(R.id.imageViewVoiceMap);

        constraintLayoutMapView.setVisibility(View.VISIBLE);
        cardViewSearch.setVisibility(View.VISIBLE);
        constraintLayoutSearch.setVisibility(View.GONE);
        cardViewPoiInfo.setVisibility(View.GONE);
        cardViewTips.setVisibility(View.GONE);
        cardViewTypes.setVisibility(View.VISIBLE);
        constraintLayoutNavigation.setVisibility(View.GONE);
        constraintLayoutMapPoi.setVisibility(View.GONE);

        recyclerViewTips.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        recyclerViewTips.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        recyclerViewTips.setItemAnimator(new DefaultItemAnimator());
        recyclerViewTips.setAdapter(poiSearchAdapter);


    }

    private void initMap() {
        if (this.baiduMap == null) {
            this.baiduMap = this.mapView.getMap();
        }
        poiSearch = PoiSearch.newInstance();
        routePlanSearch = RoutePlanSearch.newInstance();
        overlay = new IndoorRouteOverlay(baiduMap);
        poiOverlay = new MyIndoorPoiOverlay(baiduMap);
        baiduMap.setOnMarkerClickListener(poiOverlay);
    }

    /**
     * 初始化方向传感器
     */
    private void initOrientationListener() {
        myOrientationListener = new MyOrientationListener(this);
        MyLocationData.Builder builder = new MyLocationData.Builder();
        myOrientationListener.setmOnOrientationListener(x -> {
            mXDirection = (int) x;
            if (location != null) {
                builder.latitude(location.getLatitude())
                        .longitude(location.getLongitude())
                        .direction(mXDirection);
                baiduMap.setMyLocationData(builder.build());  //手机方向改变实时改变图标指向
                MyLocationConfiguration configuration = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, null);
                baiduMap.setMyLocationConfiguration(configuration);
            }
        });
    }

    /**
     * 设置地图的默认显示位置
     */
    private void setupMap() {
        // 开启地图的定位图层
        baiduMap.setMyLocationEnabled(true);
        //TODO 打开室内图，默认为关闭状态
        baiduMap.setIndoorEnable(true);
        // 初始化定位
        setupLocation();

        MyLocationConfiguration myLocationConfiguration = new MyLocationConfiguration(
                /*
                 * NORMAL 更新定位数据时不对地图做任何操作
                 * FOLLOWING 保持定位图标在地图中心
                 * COMPASS 显示定位方向圈，保持定位图标在地图中心
                 */
                MyLocationConfiguration.LocationMode.NORMAL, true, null);
        baiduMap.setMyLocationConfiguration(myLocationConfiguration);
        // 初始显示为tianjie
        moveToLocation(new LatLng(30.316040859901857, 120.33387662345238), 19);
    }

    private void initListeners() {
        baiduMap.setOnBaseIndoorMapListener(new BaiduMap.OnBaseIndoorMapListener() {
            @Override
            public void onBaseIndoorMapMode(boolean isIndoorMap,
                                            MapBaseIndoorMapInfo mapBaseIndoorMapInfo) {    // MapBaseIndoorMapInfo 室内图描述信息类
                if ((!isIndoorMap) || mapBaseIndoorMapInfo == null) {
                    MainActivity.this.mapBaseIndoorMapInfo = null;
                    stripListView.setVisibility(View.INVISIBLE);
//                    constraintLayoutNavigation.setVisibility(View.GONE);
                    return;
                } else {
                    if (mapBaseIndoorMapInfo == null) {
                        return;
                    }
                    // 设置楼层数据
                    Collections.reverse(mapBaseIndoorMapInfo.getFloors());
                    stripAdapter.setmFloorList(mapBaseIndoorMapInfo.getFloors());
                    stripListView.setVisibility(View.VISIBLE);
                    stripListView.setStripAdapter(stripAdapter);
                    System.out.println(mapBaseIndoorMapInfo.getID());
                    MainActivity.this.mapBaseIndoorMapInfo = mapBaseIndoorMapInfo;
                }

            }
        });

        // 楼层条， 点击更换楼层
        stripListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectFloor(position);
            }
        });

        // 搜索店铺框
        editTextSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    constraintLayoutMapView.setVisibility(View.INVISIBLE);
                    constraintLayoutSearch.setVisibility(View.VISIBLE);
                } else {
                    manager.hideSoftInputFromWindow(editTextSearch.getWindowToken(), 0);
//                    constraintLayoutMapView.setVisibility(View.VISIBLE);
//                    constraintLayoutSearch.setVisibility(View.INVISIBLE);
                }
            }
        });
        editTextSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {

                    // 如果搜索结果为0
                    if (poiSearchAdapter.getPoiIndoorInfos().size() == 0) {
                        Toast.makeText(MainActivity.this, "你搜索的店铺不在范围内， 请重新搜索", Toast.LENGTH_LONG).show();
                        return false;
                    }
                    searchedPoiIndoorInfos = poiSearchAdapter.getPoiIndoorInfos();
                    if (mapBaseIndoorMapInfo.getFloors() != null) {
                        selectFloor(mapBaseIndoorMapInfo.getFloors().indexOf(searchedPoiIndoorInfos.get(0).floor));
                    }
                    constraintLayoutSearch.setVisibility(View.GONE);
                    constraintLayoutMapView.setVisibility(View.VISIBLE);
                    textViewMapPoiTitle.setText("共有" + searchedPoiIndoorInfos.size() + "条结果");
                    constraintLayoutMapPoi.setVisibility(View.VISIBLE);
                    cardViewSearch.setVisibility(View.GONE);
                }
                return false;
            }
        });
        editTextSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = s.toString();
                if (keyword.isEmpty()) {
                    cardViewTypes.setVisibility(View.VISIBLE);
                    cardViewTips.setVisibility(View.INVISIBLE);
                } else {
                    cardViewTypes.setVisibility(View.INVISIBLE);
                    cardViewTips.setVisibility(View.VISIBLE);
                    poiSearch.setOnGetPoiSearchResultListener(tipListener);
                    searchShop(keyword, bid);
                }
            }
        });

        // 点击按钮定位到当前所在位置
        floatingActionButtonLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                moveToMyLocation();
            }
        });

        // OnGetPoiSearchResultListener poi检索监听器
        tipListener = new OnGetPoiSearchResultListener() {
            @Override
            public void onGetPoiResult(PoiResult poiResult) {
            }

            @Override
            public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

            }

            @Override
            public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {
//                System.out.println(poiDetailSearchResult);

            }

            @Override
            public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {
                if (poiIndoorResult == null || poiIndoorResult.error == PoiIndoorResult.ERRORNO.RESULT_NOT_FOUND) {
//                    return;
                }
/*                if(poiIndoorResult.error == SearchResult.ERRORNO.NO_ERROR) {

                }*/
                if (poiIndoorResult.getArrayPoiInfo() != null) {
                    poiSearchAdapter.setPoiIndoorInfos(poiIndoorResult.getArrayPoiInfo());
                } else {
                    poiSearchAdapter.setPoiIndoorInfos(new ArrayList<PoiIndoorInfo>());
                }
            }
        };

        routePlanSearch.setOnGetRoutePlanResultListener(new OnGetRoutePlanResultListener() {
            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

            }

            @Override
            public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

            }

            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {

            }

            @Override
            public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {
                //创建IndoorRouteOverlay实例

                if (indoorRouteResult.getRouteLines() != null && indoorRouteResult.getRouteLines().size() > 0) {
                    constraintLayoutNavigation.setVisibility(View.VISIBLE);
                    cardViewSearch.setVisibility(View.GONE);
                    routeLines = indoorRouteResult.getRouteLines();
                    int floorPosition = mapBaseIndoorMapInfo.getFloors().indexOf(startFloorId);
                    selectFloor(floorPosition);
                }
            }

            @Override
            public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

            }
        });

        baiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                System.out.println(latLng);
            }

            @Override
            public void onMapPoiClick(MapPoi mapPoi) {
            }
        });
        buttonCancelRoute.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cardViewSearch.setVisibility(View.VISIBLE);
                constraintLayoutNavigation.setVisibility(View.GONE);
                overlay.removeFromMap();
                poiOverlay.removeFromMap();
                searchedPoiIndoorInfos = null;
                routeLines = null;
            }
        });

        // 启动 NavigationActivity
        buttonNavigation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, NavigationActivity.class);

                intent.putExtra("bid", bid);
                intent.putExtra("endNodeBean", new IndoorPlanBean(clickedMapPoiInfo.uid,
                        clickedMapPoiInfo.latLng, clickedMapPoiInfo.floor, clickedMapPoiInfo.name));
                startActivityForResult(intent, 0);
                cardViewPoiInfo.setVisibility(View.GONE);
            }
        });
        poiSearchAdapter.setOnItemClickListener(new PoiSearchAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                editTextSearch.clearFocus();
                ArrayList<PoiIndoorInfo> poiIndoorInfos = new ArrayList<>();
                PoiIndoorInfo poiIndoorInfo = poiSearchAdapter.getPoiIndoorInfos().get(position);
                poiIndoorInfos.add(poiIndoorInfo);
                searchedPoiIndoorInfos = poiIndoorInfos;
                textViewPoiName.setText(poiIndoorInfo.name);
                textViewPoiAddress.setText(poiIndoorInfo.address);
                cardViewPoiInfo.setVisibility(View.VISIBLE);
                clickedMapPoiInfo = poiIndoorInfo;
                // TODO 当把商城移到别的地方时， 搜索商铺会崩溃
                int floorPosition = mapBaseIndoorMapInfo.getFloors().indexOf(poiIndoorInfo.floor);
                selectFloor(floorPosition);
                constraintLayoutSearch.setVisibility(View.GONE);
                constraintLayoutMapView.setVisibility(View.VISIBLE);
            }
        });

        // 计算路径button
        buttonStartNavigation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println(1);
                WalkRouteNodeInfo startWalkRouteNode = new WalkRouteNodeInfo();
                WalkRouteNodeInfo endWalkRouteNode = new WalkRouteNodeInfo();
//                startWalkRouteNode.setBuildingID(bid);
//                startWalkRouteNode.setFloorID("1F");
                // 步行导航起始位置
                startWalkRouteNode.setLocation(new LatLng(location.getLatitude(), location.getLongitude()));
//                startWalkRouteNode.setLocation(new LatLng(30.315759698933388, 120.334622454879));
                startWalkRouteNode.setCitycode(Integer.parseInt(location.getCityCode()));
                startWalkRouteNode.setKeyword("我的位置");
                startWalkRouteNode.setType(RouteNodeType.KEYWORD);
                endWalkRouteNode.setBuildingID(bid);
                endWalkRouteNode.setType(RouteNodeType.KEYWORD);
                endWalkRouteNode.setLocation(endNodeBean.getLocation());
                endWalkRouteNode.setFloorID(endNodeBean.getFloorId());
                endWalkRouteNode.setKeyword(endNodeBean.getName());
                endWalkRouteNode.setCitycode(Integer.parseInt(location.getCityCode()));
                WalkNaviLaunchParam walkParam = new WalkNaviLaunchParam().startNodeInfo(startWalkRouteNode).endNodeInfo(endWalkRouteNode);
                initNaviEngine(walkParam);
                System.out.println(2);
            }
        });

        // 上一层导航 <
        imageViewPreviousFloor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<IndoorRouteLine.IndoorRouteStep> allStep = routeLines.get(0).getAllStep();
                int index = allStep.indexOf(currentStep);
                if (index > 0) {
                    selectFloor(mapBaseIndoorMapInfo.getFloors().indexOf(allStep.get(index - 1).getFloorId()));
                }
            }
        });
        // 下一层导航 >
        imageViewNextFloor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<IndoorRouteLine.IndoorRouteStep> allStep = routeLines.get(0).getAllStep();
                int index = allStep.indexOf(currentStep);
                if (index < (allStep.size() - 1)) {
                    selectFloor(mapBaseIndoorMapInfo.getFloors().indexOf(allStep.get(index + 1).getFloorId()));
                }
            }
        });
        buttonCancelMapPoi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                poiOverlay.removeFromMap();
                searchedPoiIndoorInfos = new ArrayList<PoiIndoorInfo>();
                constraintLayoutMapPoi.setVisibility(View.GONE);
                cardViewSearch.setVisibility(View.VISIBLE);
            }
        });
        iatDialog.setListener(new RecognizerDialogListener() {
            @Override
            public void onResult(RecognizerResult recognizerResult, boolean b) {
                editTextSearch.setText(editTextSearch.getText() + recognizerResult.getResultString());
            }

            @Override
            public void onError(SpeechError speechError) {

            }
        });
        imageViewVoiceMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iatDialog.show();
                editTextSearch.requestFocus();
            }
        });
    }

    private void setupLocation() {
//        locationClient = new LocationClient(this);
//      通过LocationClientOption设置LocationClient相关参数
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);   // 设置发起定位请求的间隔
        option.setIsNeedAddress(true);
//      设置locationClientOption
        locationClient.setLocOption(option);
//      注册LocationListener监听器
        locationListener = new LocationListener();
        locationClient.registerLocationListener(locationListener);
//      调用LocationClient的start()方法，便可发起定位请求
        locationClient.start();
    }

    /**
     * 此处开始搜索bid内keyword的建筑
     *
     * @param keyword
     * @param bid
     */
    private void searchShop(String keyword, String bid) {
        if (bid == null) {
            Toast.makeText(this, "当前无室内图，无法搜索", Toast.LENGTH_LONG).show();
            return;
        } else {
            PoiIndoorOption poiIndoorOption = new PoiIndoorOption().poiIndoorBid(bid).poiIndoorWd(keyword);
            poiSearch.searchPoiIndoor(poiIndoorOption);   // 发起检索请求
        }

    }

    // 移动到当前所在地
    private void moveToMyLocation() {
        if (location == null) {
//            Toast.makeText(this, "location 为空！！！！！", Toast.LENGTH_SHORT).show();
            return;
        } else {
//            Toast.makeText(this, "location 没有空！！！！！太棒了", Toast.LENGTH_SHORT).show();
            baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
        }
    }

    /**
     * @param latLng 经度、纬度
     * @param zoom   地图缩放的显示级别
     */
    private void moveToLocation(LatLng latLng, Integer zoom) {
        if (zoom == null) {
            baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(latLng));
        } else {
            baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(latLng, zoom));
        }
    }

    /**
     * 计算路径按钮
     *
     * @param startNode
     * @param endNode
     */
    private void searchIndoorRoute(IndoorPlanNode startNode, IndoorPlanNode endNode) {
        endFloorId = endNode.getFloor();
        System.out.println(endFloorId);
        System.out.println(endNode.getLocation());
//        location.getAddress();
        if (location.getBuildingID() == null) {
            Toast.makeText(this, "你现在不在商场中", Toast.LENGTH_SHORT).show();
            return;
        } else {
            startNode = new IndoorPlanNode(new LatLng(location.getLatitude(), location.getLongitude()), location.getFloor());
        }
//        startFloorId = "F1";
//        startNode = new IndoorPlanNode(new LatLng(30.315759698933388, 120.334622454879), startFloorId);
//        endNode = new IndoorPlanNode(new LatLng(30.297188956770977, 120.21842045797126), endFloorId);
        IndoorRoutePlanOption indoorRoutePlanOption = new IndoorRoutePlanOption().from(startNode).to(endNode);
        routePlanSearch.walkingIndoorSearch(indoorRoutePlanOption);
    }

    private void selectFloor(int position) {
        if (mapBaseIndoorMapInfo == null) {
            return;
        }
        String floor = (String) stripAdapter.getItem(position);
        baiduMap.switchBaseIndoorMapFloor(floor, mapBaseIndoorMapInfo.getID());
        stripAdapter.setSelectedPostion(position);
        stripAdapter.notifyDataSetInvalidated();
        if (routeLines != null) {
            //为IndoorRouteOverlay实例设置数据
            overlay.setData(routeLines.get(0), floor, startFloorId, endFloorId);
            //在地图上绘制IndoorRouteOverlay
            overlay.addToMap();
            currentStep = overlay.getCurrentStep();
            if (currentStep != null) {
                textViewNavigationDetail.setText(currentStep.getInstructions());
                cardViewNavigation.setVisibility(View.VISIBLE);
            } else {
                cardViewNavigation.setVisibility(View.GONE);
            }
        }
        if (searchedPoiIndoorInfos != null) {
            poiOverlay.setData(searchedPoiIndoorInfos, floor);
            poiOverlay.addToMap();
        }
    }

    /**
     * 步行导航起终点参数类
     *
     * @param walkParam
     */
    private void initNaviEngine(final WalkNaviLaunchParam walkParam) {
        WalkNavigateHelper.getInstance().initNaviEngine(this, new IWEngineInitListener() {
            @Override
            public void engineInitSuccess() {
                System.out.println(3);
                routePlanWithWalkParam(walkParam);
            }

            @Override
            public void engineInitFail() {
                System.out.println(4);
            }
        });
    }

    private void routePlanWithWalkParam(WalkNaviLaunchParam walkParam) {
        WalkNavigateHelper.getInstance().routePlanWithRouteNode(walkParam, new IWRoutePlanListener() {
            @Override
            public void onRoutePlanStart() {

            }

            @Override
            public void onRoutePlanSuccess() {
                naviCalcRoute(0);
            }

            @Override
            public void onRoutePlanFail(WalkRoutePlanError walkRoutePlanError) {
                System.out.println(walkRoutePlanError);
                System.out.println("PERMISSION:" + PermissionUtils.getInstance().isIndoorNaviAuthorized());
            }
        });
    }

    private void naviCalcRoute(int routeIndex) {
        System.out.println(WalkNavigateHelper.getInstance());
        WalkNavigateHelper.getInstance().naviCalcRoute(routeIndex, new IWNaviCalcRouteListener() {
            @Override
            public void onNaviCalcRouteSuccess() {
                System.out.println(5);
                Intent intent = new Intent();
                // 开启步行导航
                intent.setClass(MainActivity.this, WNaviGuideActivity.class);
                startActivity(intent);
            }

            @Override
            public void onNaviCalcRouteFail(WalkRoutePlanError error) {

            }
        });
    }


    private void initVoice() {
        iatDialog = new RecognizerDialog(MainActivity.this, new InitListener() {
            @Override
            public void onInit(int i) {

            }
        });
        iatDialog.setParameter(SpeechConstant.RESULT_TYPE, "plain");
        iatDialog.setParameter(SpeechConstant.ASR_PTT, "0");
    }

    @Override
    protected void onStart() {
        super.onStart();
        myOrientationListener.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        myOrientationListener.stop();
    }

    @Override
    protected void onDestroy() {
        locationClient.stop();
        baiduMap.setMyLocationEnabled(false);
        mapView.onDestroy();
        mapView = null;
        super.onDestroy();
    }

    @Override
    // todo 对NavigationActivity返回的处理
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0: {
                if (resultCode == Activity.RESULT_OK) {
                    if (data != null) {
                        startNodeBean = data.getParcelableExtra("startNodeBean");
                        endNodeBean = data.getParcelableExtra("endNodeBean");
                        boolean startByMyPosition = data.getBooleanExtra("startByMyPosition", false);
                        boolean endByMyPosition = data.getBooleanExtra("endByMyPosition", false);
                        searchIndoorRoute(new IndoorPlanNode(null, null), new IndoorPlanNode(endNodeBean.getLocation(), endNodeBean.getFloorId()));
                    }
                }
            }
        }
    }

    // 首次打开地图时是否需要移动到中心点
    boolean isFirstLocation = false;

    class LocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mapView == null) {
                return;
            }
            if (location.getFloor() != null) {
                // 当前支持高精度室内定位
//                String buildingID = location.getBuildingID();// 百度内部建筑物ID
//                String buildingName = location.getBuildingName();// 百度内部建筑物缩写
//                String floor = location.getFloor();// 室内定位的楼层信息，如 f1,f2,b1,b2
                locationClient.startIndoorMode();// 开启室内定位模式（重复调用也没问题），开启后，定位SDK会融合各种定位信息（GPS,WI-FI，蓝牙，传感器等）连续平滑的输出定位结果；
            }
//            MyLocationData locData = new MyLocationData.Builder()
//                    .accuracy(location.getRadius())
//                    // 此处设置开发者获取到的方向信息，顺时针0-360
//                    .direction(location.getDirection())
//                    .latitude(location.getLatitude())
//                    .longitude(location.getLongitude())
//                    .build();
//            baiduMap.setMyLocationData(locData);
            // 设定为当前位置
            MainActivity.this.location = location;
            // 设定MainActivity的location
            if (isFirstLocation) {
                isFirstLocation = false;
                moveToMyLocation();
            }
//            if (MainActivity.this.location == null) {
//                MainActivity.this.location = location;
//                moveToMyLocation();
//            } else {
//                MainActivity.this.location = location;
//            }
        }
    }

    private class MyIndoorPoiOverlay extends com.baidu.mapapi.overlayutil.IndoorPoiOverlay {

        /**
         * 构造函数
         *
         * @param baiduMap 该 IndoorPoiOverlay 引用的 BaiduMap 对象
         */
        public MyIndoorPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public boolean onPoiClick(int i) {
            PoiIndoorInfo poiIndoorInfo = getPoiIndoorInfos().get(i);
            clickedMapPoiInfo = poiIndoorInfo;
            textViewPoiName.setText(poiIndoorInfo.name);
            textViewPoiAddress.setText(poiIndoorInfo.address);
            cardViewPoiInfo.setVisibility(View.VISIBLE);
            return false;
        }
    }
}
